<template>
 <div>
   <el-container>
     <el-aside width="10%">
      <side-bar :categories="categories" @category-selected="switchCategory" />
     </el-aside>
     <el-main>
       <template v-if="orders.length === 0">
         <el-skeleton />
       </template>
       <template v-else>
         <template v-for="order in filteredData">
           <order-item
               :key="order.id"
               :id="order.id"
               :addr="order.address"
               :time="order.orderTime"
               :status="order.status"
               :books="order.books"
               @send="send"
               admin
           />
         </template>
       </template>

     </el-main>
   </el-container>
 </div>
</template>

<script>
import axios from "axios";
import OrderItem from "@/components/Orders/OrderItem";
import SideBar from "@/components/books/SideBar.vue";

export default {
  name: "ManageOrdersView",
  components: {SideBar, OrderItem},
  data() {
    return {
      orders: [],
      bookCache: {},
      categories: [
        {
          id: 0,
          name: "未付款"
        },
        {
          id: 1,
          name: "已付款"
        },
        {
          id: 2,
          name: "已发货"
        },
        {
          id: 3,
          name: "已签收"
        }
      ],
      category: "all"
    }
  },
  methods: {
    async fetchBook(id) {
      let book = this.bookCache[id];
      if (book) {
        return book;
      }
      let res = await axios.get(`/api/book/fetch?id=${id}`);
      book = res.data;
      this.bookCache[book.id] = book;
      return book
    },
    async fetchOrders() {
      let res = await axios.get('/api/manage/order/fetch');
      return res.data;
    },
    async expendOrder(order) {
      const bookItems = order.books;
      let books = await Promise.all(bookItems.map(i => this.fetchBook(i.bookId)));
      books = books.map((book, index) => ({
        id: book.id,
        title: book.title,
        price: book.price,
        count: bookItems[index].cnt,
        img: book.imgUrl
      })
      );

      return {
        ...order,
        books
      }
    },
    async refresh() {
      let orders = await this.fetchOrders();
      // return await Promise.all(orders.map(val => this.expendOrder(val)))
      let expended = [];
      for (const order of orders) {
        let item = await this.expendOrder(order);
        expended.push(item);
      }
      return expended;
    },
    waitForRefresh() {
      this.refresh().then(val => {
        this.orders = val
      })
          .catch(e => {
            console.log(e);
            this.$message({
              message: "未知的错误",
              type: "error"
            });
          })
    },
    send(id) {
      axios.post(`/api/manage/order/send`, {id})
          .then(() => {
            this.$message({
              message: '发货成功！',
              type: "success"
            });
            this.waitForRefresh()
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    switchCategory(val) {
      this.category = val;
    }
  },
  computed: {
    filteredData() {
      if (this.category === "all") {
        return this.orders;
      } else {
        return this.orders.filter(val => val.status === parseInt(this.category));
      }
    }
  },
  beforeMount() {
    this.waitForRefresh()
  }
}
</script>

<style scoped>

</style>